package com.hw2;

import java.util.Collections;
import java.util.PriorityQueue;

public class NumberStream {

	
	public long getMedian(long num,PriorityQueue<Long> maxHeap,PriorityQueue<Long> minHeap){
		if(maxHeap.size()==0 || num<=maxHeap.peek()){
			maxHeap.add(num);
		}
		else 
			minHeap.add(num);
		rebalance(maxHeap,minHeap);
		if(maxHeap.size()==minHeap.size())
			return Math.min(maxHeap.peek(), minHeap.peek());
		return maxHeap.peek();
		
	}
	
	public long getMedian(PriorityQueue<Long> maxHeap,PriorityQueue<Long> minHeap){	
		if(maxHeap.size()==minHeap.size())
			return Math.min(maxHeap.peek(), minHeap.peek());
		return maxHeap.peek();
	}
	
	private void rebalance(PriorityQueue<Long> maxHeap,PriorityQueue<Long> minHeap){
		if(maxHeap.size()<minHeap.size())
			maxHeap.add(minHeap.remove());
		if(maxHeap.size()==minHeap.size()+2){
			minHeap.add(maxHeap.remove());
		}
	}
	public void getNumberSequence(){
		
        PriorityQueue<Long> maxHeap = new PriorityQueue<Long>(10, Collections.reverseOrder());
        PriorityQueue<Long> minHeap = new PriorityQueue<Long>(10);
        
        //stream numbers
        Integer[] A={56,7,12,14,10,34,67,78,34,1,-34,2,100,54,34,12,-12,-20,134};
        for(int i=0;i<A.length;i++){
        	System.out.println(getMedian((long)A[i],maxHeap,minHeap));
        	long v1=maxHeap.peek();
        	if(minHeap.size()!=0)
        		v1=minHeap.peek();
        	System.out.println();
        }
        
	}
}
